package space.xxhui.oomdemo.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.List;

import space.xxhui.oomdemo.R;
import space.xxhui.oomdemo.utils.ImageAsyncTask;
import space.xxhui.oomdemo.utils.LruCacheUtils;

/**
 * Created by hui on 2016/10/12.
 */

public class ImageAdapter extends RecyclerView.Adapter {

    private static final String TAG = "ImageAdapter";
    List data;
    Context context;

    public ImageAdapter(Context context, List data) {
        this.context = context.getApplicationContext();
        this.data = data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout,parent,false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        //修改前，把耗时操作放在onBindViewHolder，导致容易出现ANR，修改后，将操作放到AsyncTask，没有延迟就加载了
        //Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),(int)data.get(position));
        //LruCacheUtils.getInstance().addBitmapToMemoryCache(String.valueOf(data.get(position)),bitmap);
        Bitmap lruBitmap = LruCacheUtils.getInstance().getBitmapFromMemCache(String.valueOf(data.get(position)));
        if (lruBitmap==null){
            ImageAsyncTask task = new ImageAsyncTask(((ViewHolder)holder).imageView ,context);
            task.execute(String.valueOf(data.get(position)));
        }
        ((ViewHolder)holder).imageView.setImageBitmap(lruBitmap);
        //bitmap.recycle();
        Log.e(TAG, "onBindViewHolder: "+position,null );

    }

   @Override
    public int getItemCount() {
        return data.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{
        private ImageView imageView;
        public ViewHolder(View itemView) {
            super(itemView);
            imageView = (ImageView)itemView;
        }
    }
}
